/**
 * 工作流审批状态管理
 */

import { defineStore } from 'pinia'

export const useWorkflowStore = defineStore('workflow', {
  state: () => ({
    // 待审批列表
    pendingApprovals: [
      {
        id: 1,
        type: 'purchase_order',
        typeName: '采购订单',
        title: '采购订单审批',
        content: '订单号：PO20240115001，供应商：苹果供应商，金额：¥25,000',
        applicant: '张三',
        applicantId: 1,
        createTime: '2024-01-15 10:00:00',
        priority: 'high',
        amount: 25000,
        orderId: 1,
        orderNo: 'PO20240115001',
        status: 'pending',
        currentStep: 1,
        totalSteps: 2,
        approvers: [
          { id: 1, name: '李经理', role: '采购经理', status: 'pending', approveTime: null, comment: '' },
          { id: 2, name: '王总', role: '总经理', status: 'pending', approveTime: null, comment: '' }
        ]
      },
      {
        id: 2,
        type: 'transfer',
        typeName: '库存调拨',
        title: '库存调拨审批',
        content: '调拨单号：TR20240115002，从分仓库A调拨到分仓库B，数量：5台',
        applicant: '李四',
        applicantId: 2,
        createTime: '2024-01-15 14:00:00',
        priority: 'medium',
        amount: 0,
        orderId: 2,
        orderNo: 'TR20240115002',
        status: 'pending',
        currentStep: 1,
        totalSteps: 1,
        approvers: [
          { id: 3, name: '赵主管', role: '仓库主管', status: 'pending', approveTime: null, comment: '' }
        ]
      },
      {
        id: 3,
        type: 'expense',
        typeName: '费用报销',
        title: '差旅费报销',
        content: '申请人：王五，费用类型：差旅费，金额：¥3,500',
        applicant: '王五',
        applicantId: 3,
        createTime: '2024-01-15 16:30:00',
        priority: 'low',
        amount: 3500,
        orderId: 3,
        orderNo: 'EX20240115001',
        status: 'pending',
        currentStep: 1,
        totalSteps: 2,
        approvers: [
          { id: 4, name: '陈经理', role: '部门经理', status: 'pending', approveTime: null, comment: '' },
          { id: 5, name: '财务总监', role: '财务总监', status: 'pending', approveTime: null, comment: '' }
        ]
      }
    ],
    
    // 已审批列表
    approvedItems: [
      {
        id: 4,
        type: 'purchase_order',
        typeName: '采购订单',
        title: '采购订单审批',
        content: '订单号：PO20240114001，供应商：耐克供应商，金额：¥12,000',
        applicant: '张三',
        applicantId: 1,
        createTime: '2024-01-14 09:00:00',
        priority: 'medium',
        amount: 12000,
        orderId: 4,
        orderNo: 'PO20240114001',
        status: 'approved',
        currentStep: 2,
        totalSteps: 2,
        approvers: [
          { id: 1, name: '李经理', role: '采购经理', status: 'approved', approveTime: '2024-01-14 10:30:00', comment: '同意采购' },
          { id: 2, name: '王总', role: '总经理', status: 'approved', approveTime: '2024-01-14 14:20:00', comment: '批准' }
        ]
      }
    ],
    
    // 已拒绝列表
    rejectedItems: [
      {
        id: 5,
        type: 'transfer',
        typeName: '库存调拨',
        title: '库存调拨审批',
        content: '调拨单号：TR20240113001，从主仓库调拨到分仓库A，数量：50台',
        applicant: '李四',
        applicantId: 2,
        createTime: '2024-01-13 11:00:00',
        priority: 'high',
        amount: 0,
        orderId: 5,
        orderNo: 'TR20240113001',
        status: 'rejected',
        currentStep: 1,
        totalSteps: 1,
        approvers: [
          { id: 3, name: '赵主管', role: '仓库主管', status: 'rejected', approveTime: '2024-01-13 15:45:00', comment: '库存不足，无法调拨' }
        ]
      }
    ],
    
    // 审批流程配置
    workflowConfig: {
      purchase_order: {
        name: '采购订单审批',
        steps: [
          { role: '采购经理', required: true, parallel: false },
          { role: '总经理', required: true, parallel: false, condition: 'amount > 10000' }
        ]
      },
      transfer: {
        name: '库存调拨审批',
        steps: [
          { role: '仓库主管', required: true, parallel: false }
        ]
      },
      expense: {
        name: '费用报销审批',
        steps: [
          { role: '部门经理', required: true, parallel: false },
          { role: '财务总监', required: true, parallel: false, condition: 'amount > 2000' }
        ]
      }
    }
  }),

  getters: {
    // 获取所有待审批项目
    allPendingApprovals: (state) => state.pendingApprovals,
    
    // 获取所有已审批项目
    allApprovedItems: (state) => state.approvedItems,
    
    // 获取所有已拒绝项目
    allRejectedItems: (state) => state.rejectedItems,
    
    // 按类型获取待审批项目
    getPendingByType: (state) => {
      return (type) => state.pendingApprovals.filter(item => item.type === type)
    },
    
    // 按优先级获取待审批项目
    getPendingByPriority: (state) => {
      return (priority) => state.pendingApprovals.filter(item => item.priority === priority)
    },
    
    // 获取高优先级待审批项目
    highPriorityPending: (state) => {
      return state.pendingApprovals.filter(item => item.priority === 'high')
    },
    
    // 获取我的待审批项目（当前用户需要审批的）
    myPendingApprovals: (state) => {
      // 这里应该根据当前用户角色过滤
      return state.pendingApprovals.filter(item => {
        return item.approvers.some(approver => 
          approver.status === 'pending' && 
          // 这里应该检查当前用户是否有该角色
          true // 暂时返回true，实际应该检查用户角色
        )
      })
    },
    
    // 获取我申请的审批项目
    myAppliedApprovals: (state) => {
      // 这里应该根据当前用户ID过滤
      return [
        ...state.pendingApprovals,
        ...state.approvedItems,
        ...state.rejectedItems
      ].filter(item => item.applicantId === 1) // 假设当前用户ID为1
    }
  },

  actions: {
    // 提交审批申请
    submitApproval(approvalData) {
      const newApproval = {
        id: Date.now(),
        status: 'pending',
        currentStep: 1,
        createTime: new Date().toLocaleString(),
        approvers: [],
        ...approvalData
      }
      
      // 根据审批类型配置审批流程
      const config = this.workflowConfig[approvalData.type]
      if (config) {
        newApproval.totalSteps = config.steps.length
        newApproval.approvers = config.steps.map(step => ({
          id: Date.now() + Math.random(),
          name: '待分配',
          role: step.role,
          status: 'pending',
          approveTime: null,
          comment: ''
        }))
      }
      
      this.pendingApprovals.unshift(newApproval)
      return newApproval
    },
    
    // 审批通过
    approveApproval(approvalId, approverId, comment = '') {
      const approval = this.pendingApprovals.find(item => item.id === approvalId)
      if (!approval) return false
      
      const approver = approval.approvers.find(ap => ap.id === approverId)
      if (!approver) return false
      
      // 更新审批人状态
      approver.status = 'approved'
      approver.approveTime = new Date().toLocaleString()
      approver.comment = comment
      
      // 检查是否所有审批人都已审批
      const allApproved = approval.approvers.every(ap => ap.status === 'approved')
      if (allApproved) {
        // 所有审批完成，移动到已审批列表
        approval.status = 'approved'
        this.pendingApprovals = this.pendingApprovals.filter(item => item.id !== approvalId)
        this.approvedItems.unshift(approval)
      } else {
        // 更新当前步骤
        approval.currentStep = approval.approvers.filter(ap => ap.status === 'approved').length + 1
      }
      
      return true
    },
    
    // 审批拒绝
    rejectApproval(approvalId, approverId, comment = '') {
      const approval = this.pendingApprovals.find(item => item.id === approvalId)
      if (!approval) return false
      
      const approver = approval.approvers.find(ap => ap.id === approverId)
      if (!approver) return false
      
      // 更新审批人状态
      approver.status = 'rejected'
      approver.approveTime = new Date().toLocaleString()
      approver.comment = comment
      
      // 审批被拒绝，移动到已拒绝列表
      approval.status = 'rejected'
      this.pendingApprovals = this.pendingApprovals.filter(item => item.id !== approvalId)
      this.rejectedItems.unshift(approval)
      
      return true
    },
    
    // 撤销审批申请
    cancelApproval(approvalId) {
      const index = this.pendingApprovals.findIndex(item => item.id === approvalId)
      if (index > -1) {
        this.pendingApprovals.splice(index, 1)
        return true
      }
      return false
    },
    
    // 重新提交审批申请
    resubmitApproval(approvalId) {
      const approval = this.rejectedItems.find(item => item.id === approvalId)
      if (!approval) return false
      
      // 重置审批状态
      approval.status = 'pending'
      approval.currentStep = 1
      approval.approvers.forEach(approver => {
        approver.status = 'pending'
        approver.approveTime = null
        approver.comment = ''
      })
      
      // 移动到待审批列表
      this.rejectedItems = this.rejectedItems.filter(item => item.id !== approvalId)
      this.pendingApprovals.unshift(approval)
      
      return true
    },
    
    // 获取审批详情
    getApprovalDetail(approvalId) {
      const allApprovals = [
        ...this.pendingApprovals,
        ...this.approvedItems,
        ...this.rejectedItems
      ]
      return allApprovals.find(item => item.id === approvalId)
    },
    
    // 更新审批流程配置
    updateWorkflowConfig(type, config) {
      this.workflowConfig[type] = config
    },
    
    // 获取审批统计
    getApprovalStats() {
      return {
        pending: this.pendingApprovals.length,
        approved: this.approvedItems.length,
        rejected: this.rejectedItems.length,
        highPriority: this.pendingApprovals.filter(item => item.priority === 'high').length
      }
    }
  }
})
